<template>
<!-- 学生会组织 -->
  <div class="app-container">
    <!-- <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="校学生会" name="first">
        </el-tab-pane>
        <el-tab-pane label="二级学院学生会" name="second"></el-tab-pane>
    </el-tabs> -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期" prop="schoolYear">
          <el-select
            v-model="queryParams.schoolYear"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
                v-for="option in schoolYearList"
                :key="option.schoolYearId"
                :label="option.schoolYearId"
                :value="option.schoolYearId"
              />
          </el-select>
        </el-form-item>
      <el-form-item label="名称" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="指导单位" prop="unitCode">
        <el-select
          v-model="queryParams.unitCode"
          placeholder="请选择"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="(dict,index) in unitNameList"
            :key="index"
            :label="dict.unitName"
            :value="dict.unitCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="级别" prop="grade">
        <el-select
          v-model="queryParams.grade"
          placeholder="请选择"
          clearable
          style="width: 240px"
        >
          <el-option
              v-for="dict in dict.type.org_grade"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
            <!-- <el-button
              style="padding: 8px;"
              type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
              v-hasPermi="['organ:studentUnionOrgan:del']"
              @click='handleDelete'
            >删除</el-button> -->
          </el-col>
        </el-row>
    </el-form>
    

    <el-table border v-loading="loading" :data="orgList">
            
      <el-table-column label="组织名称" align="center" prop="orgName" />
      <!-- <el-table-column label="学院" align="center" prop="unitName" /> -->
     <el-table-column label="指导单位" align="center" prop="unitName" />
<!--      <el-table-column label="班级" align="center" prop="classNo" />
      <el-table-column label="年级" align="center" prop="grade" /> -->
     <el-table-column label="级别" align="center" prop="grade" />
      <el-table-column label="指导教师" align="center" prop="teacherName" />
      <el-table-column label="学生管理员" align="center" prop="studentName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width='500'>
        <template slot-scope="scope">
          <el-button
            style="padding: 6px; margin-right: 6px"
            size="mini"
            type="primary"
            v-hasPermi="['organ:studentOrgan:setTeacher']"
            @click="handleUpdateDetail(scope.row)"
            >修改</el-button
          >
          <router-link
            style="margin-right: 6px"
            :to="'/organ/studentUnionOrgan-data/index/' + scope.row.orgId"
            class="link-type"
          >
          <el-button
            style="padding: 8px;margin-right: 8px;"
            size="mini"
            type="primary"
            v-hasPermi="['organ:studentUnionOrgan:detail']"
          >详情</el-button>
          </router-link>
          <el-button
            style="padding: 8px;margin-right: 8px;"
            size="mini"
            type="primary"
            v-hasPermi="['organ:studentUnionOrgan:setTeacher']"
            @click="handleUpdate1(scope.row)"
          >设置学生管理员</el-button>
          <el-button
            style="padding: 8px;margin-right: 8px;"
            size="mini"
            type="primary"
            v-hasPermi="['organ:studentUnionOrgan:setTeacher']"
            @click="handleUpdate(scope.row)"
          >设置指导教师</el-button>
          <el-button size="mini" style="padding: 8px;" type="success" @click="code1(scope.row)">二维码</el-button>
            <el-button
              style="padding: 8px;"
              size="mini"
              type="danger"
              v-hasPermi="['organ:studentUnionOrgan:del']"
              @click='handleDelete(scope.row)'
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!--修改 -->
    <el-dialog :title="title" :visible.sync="updateOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="组织名称" prop="orgName">
          <el-input v-model="form.orgName"  placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="指导单位" prop="unitCode">
          <el-select
            v-model="form.unitCode"
            placeholder="请选择"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="(dict,index) in unitNameList"
              :key="index"
              :label="dict.unitName"
              :value="dict.unitCode"
            >{{dict.unitName}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生管理员" prop="studentId">
          <el-select
              v-model="form.studentId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="searchLoading">
              <el-option
                v-for="(item,index) in options1"
                :key="index"
                :label="item.label"
                :value="item.label.substring(0,item.label.lastIndexOf('-'))">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="指导老师" prop="teacherId">
          <el-select
              v-model="form.teacherId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod2"
              :loading="searchLoading">
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.label.substring(0,item.label.lastIndexOf('-'))">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="级别" prop="grade">
          <el-select
            v-model="form.grade"
            placeholder="请选择"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.org_grade"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="社团简介" prop="remark">
          <el-input v-model="form.remark" type='textarea'  placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormUpdateDetail">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置指导教师 -->
    <el-dialog title="添加指导教师" :visible.sync="teacherOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="指导老师" prop="teacherId">
          <el-select
              v-model="form.teacherId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod2"
              :loading="searchLoading">
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.label.substring(0,item.label.lastIndexOf('-'))">
              </el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormTeacher">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加学生管理员" :visible.sync="teacherOpen1" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学生管理员" prop="studentId">
          <el-select
              v-model="form.studentId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="searchLoading">
              <el-option
                v-for="(item,index) in options1"
                :key="index"
                :label="item.label"
                :value="item.label.substring(0,item.label.lastIndexOf('-'))">
              </el-option>
            </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormStudent">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 二维码对话框 -->
    <el-dialog :title="title" :visible.sync="QRCode" width="380px" append-to-body>
      <el-card>
        <el-image id="erCode" v-if="QRCodeImage" style="width: 300px; height: 300px" :src="QRCodeImage"
          :preview-src-list="[QRCodeImage]" fit="cover">
        </el-image>
        <el-button type="primary" @click="openUrl(QRCodeImage, title)">点击下载</el-button>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrg,
  getOrg,
  delOrg,
  addOrg,
  updateOrg,
  getstudentmanager,
  getTeacherManager,
  unitNameList,
  setteachermanager,
  setstudentmanager,
  showQrCode,
  downloadImgs
} from "@/api/organ/studentUnionOrgan";
import { mapGetters } from 'vuex';
import { MessageBox, Message } from 'element-ui';
import { GetYearList } from '@/api/organ/organ';
export default {
  name: "Org",
  dicts: ['sys_normal_disable', 'org_grade'],
  computed: {
    ...mapGetters(['roles', 'name']),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      orgIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 组织信息表格数据
      orgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type:3,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // studentId: [
        //   { required: true, message: '学生管理员不能为空', trigger: 'blur' }
        // ],
        orgName: [
          { required: true, message: '组织名称不能为空', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '老师不能为空', trigger: 'blur' }
        ],
        unitCode: [
          { required: true, message: '指导单位不能为空', trigger: 'blur' }
        ],
        // remark: [
        //   { required: true, message: '学生会简介不能为空', trigger: 'blur' }
        // ]
      },
      options: [],
      options1: [],
      value: [],
      list: [],
      searchLoading: false,
      unitNameList:[],
      orgForm:{},
      activeName:'first',
      teacherOpen:false,
      teacherOpen1:false,
      updateOpen:false,
      schoolYearList: [],
      QRCodeImage:[],
      QRCode:false
    };
  },
  created() {
    GetYearList().then(response => { 
      this.schoolYearList = response.rows;
      for (let i  = 0; i  < response.total; i ++) {
        if(response.rows[i].defaultValue == "1"){
          console.log(response.rows[i],"year")
          this.queryParams.schoolYear = response.rows[i].schoolYearId;
        }
      }
    });
     /** 学院下拉框 */
    unitNameList().then(response => {
      this.unitNameList = response.rows;
    });
    this.getList();

  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
        this.orgIds = selection.map(item => item.orgId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
    },
    // 指导单位赋值
    changeValue(event){
      console.log(event,"valllll")
      this.form.unitCode=event.sponsorCode
      this.form.unitName=event.sponsorName
    },
    /** 查询组织信息列表 */
    getList() {
      this.loading = true;
        listOrg(this.queryParams).then(response => {
             this.orgList = response.rows;
             this.total = response.total;
          //  this.orgList.push(...response.rows);
          // this.total = this.total + response.total;
           this.loading = false;
        });
    },
    // 判断是否能设置学生
    canWrite(row) {
      console.log(row);
      var isCanWrite = false;
      if (this.roles) {
        console.log(this.roles, 'roles');
        for (let i = 0; i < this.roles.length; i++) {
          if (
            this.roles[i] == 'student-school' ||
            this.roles[i] == 'common' ||
            this.roles[i] == 'admin'
          ) {
            isCanWrite = true;
            break;
          }
            if (this.name == row.teacherId) {
              isCanWrite = true;
              break;
            }
        }
      }
      console.log(isCanWrite, 'isCanWrite');
      return isCanWrite;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.teacherOpen = false;
      this.teacherOpen1 = false;
      this.updateOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        unitName: null,
        unitCode: null,  
        type: 3,
        teacherId: null,
        remark: null,
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams.orgName = ''
      this.queryParams.unitName = ''
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.options = []
      this.options1 = []
      this.reset();
      this.updateOpen = true;
      this.title = "添加组织信息";
    },
    /** 修改操作 */
    handleUpdateDetail(row) {
      console.log(row,"row")
      this.reset();
      this.form=row;
      this.updateOpen = true;
      this.title = "修改";
    },
    /** 设置管理员操作 */
    handleUpdate(row) {
      this.reset();
      this.form.orgId=row.orgId;
      this.teacherOpen = true;
      this.options = []
      this.title = "设置指导教师";
    },
    handleUpdate1(row) {
      this.reset();
      this.form.orgId=row.orgId;
      this.teacherOpen1 = true;
      this.options1 = []
      this.title = "设置学生管理员";
    },
    /** 设置老师 */
    submitFormTeacher() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orgId != null) {
            setteachermanager(this.form).then(response => {
              if(response.code==200){
              this.$modal.msgSuccess("设置成功");
              this.teacherOpen = false;
              this.getList();
              }
            });
          }else{

          }
        }
      });
    },
    submitFormStudent() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orgId != null) {
            setstudentmanager(this.form).then(response => {
              if(response.code==200){
              this.$modal.msgSuccess("设置成功");
              this.teacherOpen1 = false;
              this.getList();
              }
            });
          }else{

          }
        }
      });
    },
    code1(row){
      this.title = row.orgName
      showQrCode(row.orgId).then(res=>{
        console.log(res);
        if (res.code == 200) {
          // Message({
          //   message: '二维码已生成',
          //   type: 'success',
          // });
          this.QRCodeImage = res.msg;

          this.QRCode = true;
        }
      });
      
    },
    // 下载二维码
    openUrl (fileName, title){
      const dataurl = document.getElementById('erCode').src//选择图片id
      // this.downloadBase64(dataurl, this.erCode_name)
      const a = document.createElement('a')
      a.href = dataurl
      a.download = title + '.jpg';
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orgId != null) {
            setstudentmanager(this.form).then(response => {
              if(response.code==200){
              this.$modal.msgSuccess("设置成功");
              this.open = false;
              this.getList();
              }
            });
          }else{

          }
        }
      });
    },

    // 添加学生会确认
    submitFormUpdateDetail(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orgId != null) {
            updateOrg(this.form).then(response => {
              if(response.code==200){
                this.$modal.msgSuccess("修改成功");
                this.updateOpen = false;
                this.getList();
              }
            });
          }else{
            addOrg(this.form).then(response => {
              if(response.code==200){
              this.$modal.msgSuccess("添加成功");
              this.updateOpen = false;
              this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orgIds = row.orgId || this.orgIds;
      this.$modal.confirm('是否确认删除组织名称为"' + row.orgName + '"的数据项？').then(function() {
        return delOrg(orgIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/org/export', {
        ...this.queryParams
      }, `org_${new Date().getTime()}.xlsx`)
    },
    /** 查询学生管理员 */
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        getstudentmanager(query).then(response => {
          this.loading = false;
          this.options1 = response.rows.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        });
      } else {
        this.options = [];
      }
    },
    /** 查询教师管理员 */
    remoteMethod2(query) {
      if (query !== '') {
        this.loading = true;
        getTeacherManager(query).then(response => {
          this.loading = false;
          this.options = response.rows.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        });
      } else {
        this.options = [];
      }
    },
    /** 导出
     */
    handleCommand(command) {
      this.queryParams.schoolYear = command;
      this.download('committee/org/export2', {
        ...this.queryParams
      }, `org_${new Date().getTime()}.xlsx`)
    },
    /** 切换标签卡 */
    handleClick(tab, event) {
      if(tab.index=='0'){

        this.getList();
      }else{
        this.getList();
      }
    }
  }
};
</script>
